var zTree;
var setting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/eduget/getEduClassTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    callback: {
        onClick: zTreeOnClick
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "sortLevel",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    }
};

var setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/eduget/getEduClassTreeForSelect",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "sortLevel",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            if (treeNode.isParent == false) {
                let zTree = $.fn.zTree.getZTreeObj("menuTree");
                let nodes = zTree.getSelectedNodes();
                let strArr = [];
                let valArr = [];
                let depArr = [];
                nodes.sort(function compare(a, b) {
                    return a.id - b.id;
                });
                for (let i = 0; i < nodes.length; i++) {
                    depArr.push(nodes[i].sortLevel);
                    strArr.push(nodes[i].sortName);
                    valArr.push(nodes[i].sortId);
                }
                $("#departmentsId").val(strArr.join(","));
                $("#departmentsId").attr("data-major-value", valArr.join(","));
                $("#departmentsId").attr("data-value", depArr.join(","));
            }
        }
    }
};

$(function () {
    getAllEduGradeList();
    $.ajax({
        url: "/ret/eduget/getEduClassTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            zTree = $.fn.zTree.init($("#tree"), setting, data);// 初始化树节点时，添加同步获取的数据
            $.fn.zTree.init($("#menuTree"), setting1, data);
        }
    });
    $.ajax({
        url: "/ret/eduget/getEduClassTreeForSelect",
        type: "post",
        dataType: "json",
        success: function (data) {
            $.fn.zTree.init($("#menuTree"), setting1, data);
        }
    });
    $("#createbut").unbind("click").click(function () {
        addEduClass();
    });
    $("#cbut").unbind("click").click(function () {
        $("#datalist").hide();
        $("#creatediv").show();
        document.getElementById("form").reset();
        $("#departmentsId").attr("data-value", "");
        $("#createbut").show();
        $("#updatabut").hide();
    });
    $("#departmentsId").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });
    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });

    $(".js-class-all").unbind("click").click(function () {
        $("#creatediv").hide();
        $("#datalist").show();
        $("#myTable").bootstrapTable('destroy');
        query("", "");
    })

    $(".js-simple-query").unbind("click").click(function () {
        $("#myTable").bootstrapTable("refresh");
    })
    getEduSemesterListForSelect();
    query("", "");
});

function zTreeOnClick(event, treeId, treeNode) {
    if (treeNode.isParent == false) {
        $("#creatediv").hide();
        $("#datalist").show();
        $("#myTable").bootstrapTable('destroy');
        if (treeNode.sortId == "0") {
            query("", "");
        } else {
            query(treeNode.sortLevel, treeNode.sortId);
        }
    }
}

function delEduClass(classId) {
    if (confirm("确定删除当前班级吗？")) {
        $.ajax({
            url: "/set/eduset/deleteEduClass",
            type: "post",
            dataType: "json",
            data: {
                classId: classId
            },
            success: function (data) {
                if (data.status == 200) {
                    layer.msg(sysmsg[data.msg]);
                    location.reload();
                } else {
                    console.log(data.msg);
                }
            }
        });
    } else {
        return;
    }
}

function addEduClass() {
    $.ajax({
        url: "/set/eduset/insertEduClass",
        type: "post",
        dataType: "json",
        data: {
            sortNo: $("#sortNo").val(),
            className: $("#className").val(),
            semesterId: $("#semesterId").val(),
            majorId: $("#departmentsId").attr("data-major-value"),
            gradeId: $("#gradeId").val(),
            departmentsId: $("#departmentsId").attr("data-value"),
            headmaster: $("#headmaster").attr("data-value"),
            courseId: $("#courseId").attr("data-value"),
            roomNo: $("#roomNo").val(),
            userCount: $("#userCount").val(),
            status: $("#status").val(),
            address: $("#address").val(),
            remark: $("#remark").val()
        },
        success: function (data) {
            if (data.status == 200) {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            } else {
                console.log(data.msg);
            }
        }
    });
}

function updateEduClass(classId) {
    $.ajax({
        url: "/set/eduset/updateEduClass",
        type: "post",
        dataType: "json",
        data: {
            classId: classId,
            sortNo: $("#sortNo").val(),
            className: $("#className").val(),
            semesterId: $("#semesterId").val(),
            majorId: $("#departmentsId").attr("data-major-value"),
            gradeId: $("#gradeId").val(),
            departmentsId: $("#departmentsId").attr("data-value"),
            headmaster: $("#headmaster").attr("data-value"),
            courseId: $("#courseId").attr("data-value"),
            roomNo: $("#roomNo").val(),
            userCount: $("#userCount").val(),
            status: $("#status").val(),
            address: $("#address").val(),
            remark: $("#remark").val()
        },
        success: function (data) {
            if (data.status == 200) {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            } else {
                console.log(data.msg);
            }
        }
    });
}


function query(majorId, gradeId) {
    $("#myTable").bootstrapTable({
        url: '/ret/eduget/getEduClassList?majorId=' + majorId + "&gradeId=" + gradeId,
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'classId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        },
            {
                field: 'num',
                title: '序号',//标题  可不加
                width: '50px',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
            {
                field: 'title',
                title: '学期',
                width: '100px'
            }, {
                field: 'className',
                title: '班级名称',
                sortable: true,
                width: '100px'
            },
            {
                field: 'departmentsName',
                title: '所属院系',
                width: '150px',
            },
            {
                field: 'majorName',
                title: '专业',
                width: '150px',
            },
            {
                field: 'status',
                title: '状态',
                width: '50px',
                align: "center",
                formatter: function (value, row, index) {
                    if (value == "1") {
                        return "<a href=\"javascript:void(0);\" class=\"btn btn-success btn-xs\">正常</a>";
                    } else if (value == "0") {
                        return "<a href=\"javascript:void(0);\" class=\"btn btn-yellow btn-xs\">停班</a>";
                    } else {
                        return "<a href=\"javascript:void(0);\" class=\"btn btn-danger btn-xs\">未知</a>";
                    }
                }
            },
            {
                field: 'roomNo',
                width: '100px',
                title: '教室门牌'
            },
            {
                field: 'address',
                title: '地址',
                width: '200px',
            },
            {
                field: 'headmasterUserName',
                title: '班主任',
                width: '100px',
            },
            {
                field: 'opt',
                title: '操作',
                align: 'center',
                width: '100px',
                formatter: function (value, row, index) {
                    return createOptBtn(row.classId);
                }
            }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
                layer.msg(sysmsg[res.msg]);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function createOptBtn(classId) {
    var html = "<a href=\"javascript:void(0);edit('" + classId + "')\" class=\"btn btn-sky btn-xs\" >修改</a>&nbsp;&nbsp;<a href=\"javascript:void(0);delEduClass('" + classId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>";
    return html;
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        semesterId: $("#semesterIdQuery").val()
    };
    return temp;
};

function edit(classId) {
    $("#datalist").hide()
    $("#creatediv").show();
    document.getElementById("form").reset();
    $("#departmentsId").attr("data-value", "");
    $("#departmentsId").attr("data-major-value", "");
    $("#courseId").attr("data-value", "");
    $.ajax({
        url: "/ret/eduget/getEduClassById",
        type: "post",
        dataType: "json",
        data: {
            classId: classId
        },
        success: function (data) {
            console.log(data);
            if (data.status == "200") {
                var v = data.list;
                for (let name in v) {
                    if (name == "departmentsId") {
                        $("#departmentsId").attr("data-value", v["departmentsId"]);
                        $.ajax({
                            url: "/ret/eduget/getEduDepartmentsById",
                            type: "post",
                            dataType: "json",
                            data: {
                                departmentsId: v["departmentsId"]
                            },
                            success: function (data) {
                                if (data.status == "200") {
                                    if (data.list) {
                                        $("#departmentsId").val(data.list.departmentsName);
                                    } else {
                                        $("#departmentsId").val("");
                                    }
                                }
                            }
                        });
                    } else if (name == "majorId") {
                        $("#departmentsId").attr("data-major-value", v["majorId"]);
                    } else if (name == "headmaster") {
                        $("#headmaster").attr("data-value", v["headmaster"]);
                        $("#headmaster").val(getUserNameByStr(v["headmaster"]));
                    } else if (name == "courseId") {
                        $("#courseId").attr("data-value", v["courseId"]);
                        $("#courseId").val(getCourseName(v["courseId"]));
                    } else {
                        $("#" + name).val(v[name]);
                    }
                }
            } else {
                console.log(data.msg);
            }

        }
    });
    $("#createbut").hide();
    $("#updatabut").show();
    $("#updatabut").unbind("click").click(function () {
        updateEduClass(classId);
    });
}


function getEduSemesterListForSelect() {
    $.ajax({
        url: "/ret/eduget/getEduSemesterListForSelect",
        type: "post",
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.status == "200") {
                var infoList = data.list;
                $("#semesterIdQuery").append("<option value=\"\">全部</option>")
                for (var i = 0; i < infoList.length; i++) {
                    $("#semesterIdQuery").append("<option value=\"" + infoList[i].semesterId + "\">" + infoList[i].title + "</option>");
                    $("#semesterId").append("<option value=\"" + infoList[i].semesterId + "\">" + infoList[i].title + "</option>");
                }
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }
        }
    });
}


function getAllEduGradeList() {
    $.ajax({
        url: "/ret/eduget/getAllEduGradeList",
        type: "post",
        dataType: "json",
        data: {},
        success: function (data) {
            if (data.status == 200) {
                for (var i = 0; i < data.list.length; i++) {
                    $("#gradeId").append("<option value='" + data.list[i].gradeId + "'>" + data.list[i].title + "</option>");
                }
            } else if (data.status == 100) {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }
        }
    });
}
